"""
Generated Content Model
生成内容模型 - 存储生成的内容元数据、文件信息、版本控制
"""

import uuid
from enum import Enum

from sqlalchemy import Column, String, DateTime, Integer, Boolean, Text, ForeignKey, JSON, Numeric
from sqlalchemy.dialects.postgresql import UUID
from sqlalchemy.sql import func
from sqlalchemy.orm import relationship

from ..core.database import Base


class ContentStatus(str, Enum):
    """内容状态枚举"""
    PENDING = "pending"           # 等待生成
    GENERATING = "generating"     # 生成中
    COMPLETED = "completed"       # 已完成
    FAILED = "failed"             # 生成失败
    PROCESSING = "processing"     # 后处理中
    READY = "ready"               # 可下载
    ARCHIVED = "archived"         # 已归档
    DELETED = "deleted"           # 已删除


class ContentFormat(str, Enum):
    """内容格式枚举"""
    PNG = "png"
    JPG = "jpg"
    JPEG = "jpeg"
    GIF = "gif"
    WEBP = "webp"
    MP4 = "mp4"
    AVI = "avi"
    MOV = "mov"
    WEBM = "webm"
    MP3 = "mp3"
    WAV = "wav"
    M4A = "m4a"
    FLAC = "flac"
    TXT = "txt"
    JSON = "json"


class ContentQuality(str, Enum):
    """内容质量枚举"""
    LOW = "low"
    MEDIUM = "medium"
    HIGH = "high"
    ULTRA = "ultra"


class GeneratedContent(Base):
    """生成内容模型"""

    __tablename__ = "generated_contents"

    id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
    
    # 关联信息
    user_id = Column(
        UUID(as_uuid=True), 
        ForeignKey("users.id", ondelete="CASCADE"), 
        nullable=False,
        index=True
    )
    creation_request_id = Column(
        UUID(as_uuid=True), 
        ForeignKey("creation_requests.id", ondelete="SET NULL"), 
        nullable=True,
        index=True
    )
    folder_id = Column(
        UUID(as_uuid=True), 
        ForeignKey("folders.id", ondelete="SET NULL"), 
        nullable=True,
        index=True
    )

    # 基本信息
    title = Column(String(200), nullable=True)
    description = Column(Text, nullable=True)
    content_type = Column(String(20), nullable=False, index=True)  # image, video, audio, text
    format = Column(String(10), nullable=False, index=True)  # png, mp4, mp3, txt等
    
    # 文件信息
    file_name = Column(String(255), nullable=False)
    file_size_bytes = Column(Integer, nullable=False, default=0)
    file_path = Column(String(500), nullable=False)
    file_url = Column(String(500), nullable=True)
    thumbnail_path = Column(String(500), nullable=True)
    thumbnail_url = Column(String(500), nullable=True)
    
    # 内容规格
    width = Column(Integer, nullable=True)
    height = Column(Integer, nullable=True)
    duration = Column(Integer, nullable=True)  # 视频/音频时长（秒）
    fps = Column(Numeric(3, 1), nullable=True)  # 视频帧率
    bitrate = Column(Integer, nullable=True)  # 比特率
    resolution = Column(String(20), nullable=True)  # 分辨率描述 (如: 1920x1080)
    
    # 生成信息
    prompt = Column(Text, nullable=True)  # 使用的提示词
    negative_prompt = Column(Text, nullable=True)  # 负面提示词
    ai_provider = Column(String(50), nullable=False)  # AI提供商
    ai_model = Column(String(100), nullable=True)  # AI模型
    model_version = Column(String(50), nullable=True)  # 模型版本
    seed = Column(Integer, nullable=True)  # 随机种子
    
    # 生成参数（JSON存储）
    generation_parameters = Column(JSON, default=dict)
    
    # 质量评估
    quality_score = Column(Numeric(3, 2), nullable=True)  # 质量评分 (0.00-10.00)
    quality_rating = Column(String(10), nullable=True)  # 质量等级
    nsfw_score = Column(Numeric(3, 2), nullable=True)  # NSFW评分
    is_nsfw = Column(Boolean, default=False)  # 是否为NSFW内容
    
    # 状态管理
    status = Column(String(20), nullable=False, default="pending", index=True)
    is_public = Column(Boolean, default=False)  # 是否公开
    is_favorite = Column(Boolean, default=False)  # 是否收藏
    is_downloaded = Column(Boolean, default=False)  # 是否已下载
    download_count = Column(Integer, default=0)  # 下载次数
    view_count = Column(Integer, default=0)  # 查看次数
    
    # 版本控制
    version = Column(Integer, default=1)  # 版本号
    parent_content_id = Column(
        UUID(as_uuid=True), 
        ForeignKey("generated_contents.id", ondelete="SET NULL"), 
        nullable=True,
        index=True
    )  # 父内容ID（用于版本历史）
    is_latest_version = Column(Boolean, default=True)  # 是否为最新版本
    
    # 元数据
    tags = Column(JSON, default=list)  # 标签列表
    content_metadata = Column(JSON, default=dict)  # 其他元数据（避免与SQLAlchemy的metadata冲突）
    
    # 处理信息
    processing_time_seconds = Column(Integer, nullable=True)  # 处理时间
    worker_id = Column(String(100), nullable=True)  # 处理的工作节点
    
    # 错误信息
    error_message = Column(Text, nullable=True)
    error_code = Column(String(50), nullable=True)
    
    # 时间戳
    created_at = Column(DateTime, default=func.now(), index=True)
    updated_at = Column(DateTime, default=func.now(), onupdate=func.now())
    generated_at = Column(DateTime, nullable=True)  # 生成完成时间
    expires_at = Column(DateTime, nullable=True)  # 过期时间
    
    # 关系
    user = relationship("User", back_populates="generated_contents")
    creation_request = relationship("CreationRequest", back_populates="generated_contents")
    folder = relationship("Folder", back_populates="contents")
    parent_content = relationship("GeneratedContent", remote_side=[id], back_populates="child_versions")
    child_versions = relationship("GeneratedContent", back_populates="parent_content")
    content_tags = relationship("ContentTag", secondary="content_tag_associations", back_populates="contents")
    task_queues = relationship("TaskQueue", back_populates="related_content")
    system_logs = relationship("SystemLog", back_populates="related_content")

    def __repr__(self):
        return f"<GeneratedContent(id={self.id}, user_id={self.user_id}, type={self.content_type}, format={self.format})>"

    @property
    def file_size_mb(self) -> float:
        """文件大小（MB）"""
        return self.file_size_bytes / (1024 * 1024)

    @property
    def file_size_readable(self) -> str:
        """可读的文件大小"""
        size = self.file_size_bytes
        for unit in ['B', 'KB', 'MB', 'GB']:
            if size < 1024.0:
                return f"{size:.1f} {unit}"
            size /= 1024.0
        return f"{size:.1f} TB"

    @property
    def is_image(self) -> bool:
        """是否为图片"""
        return self.content_type == "image"

    @property
    def is_video(self) -> bool:
        """是否为视频"""
        return self.content_type == "video"

    @property
    def is_audio(self) -> bool:
        """是否为音频"""
        return self.content_type == "audio"

    @property
    def is_text(self) -> bool:
        """是否为文本"""
        return self.content_type == "text"

    @property
    def is_completed(self) -> bool:
        """是否已完成"""
        return self.status == ContentStatus.COMPLETED

    @property
    def is_failed(self) -> bool:
        """是否失败"""
        return self.status == ContentStatus.FAILED

    @property
    def is_ready(self) -> bool:
        """是否可下载"""
        return self.status == ContentStatus.READY

    @property
    def has_thumbnail(self) -> bool:
        """是否有缩略图"""
        return bool(self.thumbnail_path or self.thumbnail_url)

    @property
    def aspect_ratio(self) -> str:
        """宽高比"""
        if not self.width or not self.height:
            return "unknown"
        
        # 计算最简宽高比
        import math
        gcd = math.gcd(self.width, self.height)
        w_ratio = self.width // gcd
        h_ratio = self.height // gcd
        
        return f"{w_ratio}:{h_ratio}"

    def get_generation_info(self) -> dict:
        """获取生成信息"""
        return {
            "prompt": self.prompt,
            "negative_prompt": self.negative_prompt,
            "ai_provider": self.ai_provider,
            "ai_model": self.ai_model,
            "model_version": self.model_version,
            "seed": self.seed,
            "parameters": self.generation_parameters or {},
            "processing_time": self.processing_time_seconds,
        }

    def get_file_info(self) -> dict:
        """获取文件信息"""
        return {
            "file_name": self.file_name,
            "file_size_bytes": self.file_size_bytes,
            "file_size_mb": round(self.file_size_mb, 2),
            "file_size_readable": self.file_size_readable,
            "format": self.format,
            "width": self.width,
            "height": self.height,
            "duration": self.duration,
            "fps": float(self.fps) if self.fps else None,
            "bitrate": self.bitrate,
            "resolution": self.resolution,
            "aspect_ratio": self.aspect_ratio,
        }

    def get_quality_info(self) -> dict:
        """获取质量信息"""
        return {
            "quality_score": float(self.quality_score) if self.quality_score else None,
            "quality_rating": self.quality_rating,
            "nsfw_score": float(self.nsfw_score) if self.nsfw_score else None,
            "is_nsfw": self.is_nsfw,
        }

    def mark_as_completed(self, file_path: str, file_size: int, **kwargs) -> None:
        """标记为完成"""
        self.status = ContentStatus.COMPLETED
        self.file_path = file_path
        self.file_size_bytes = file_size
        self.generated_at = func.now()
        
        # 更新其他字段
        for key, value in kwargs.items():
            if hasattr(self, key):
                setattr(self, key, value)

    def mark_as_failed(self, error_message: str, error_code: str = None) -> None:
        """标记为失败"""
        self.status = ContentStatus.FAILED
        self.error_message = error_message
        if error_code:
            self.error_code = error_code

    def increment_download_count(self) -> None:
        """增加下载次数"""
        self.download_count += 1
        self.is_downloaded = True

    def increment_view_count(self) -> None:
        """增加查看次数"""
        self.view_count += 1

    def add_tag(self, tag: str) -> None:
        """添加标签"""
        tags = self.tags or []
        if tag not in tags:
            tags.append(tag)
            self.tags = tags

    def remove_tag(self, tag: str) -> bool:
        """移除标签"""
        tags = self.tags or []
        if tag in tags:
            tags.remove(tag)
            self.tags = tags
            return True
        return False

    def set_as_latest_version(self) -> None:
        """设置为最新版本"""
        self.is_latest_version = True
        
    def unset_as_latest_version(self) -> None:
        """取消最新版本标记"""
        self.is_latest_version = False